﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Reflection;

namespace Extensil.Processor.Extensibility
{
    public sealed class ConfigSystem :IInternalConfigSystem
    {
        readonly IInternalConfigSystem baseconf;

        public static void Install()
        {
            object o = ConfigurationManager.AppSettings;
            FieldInfo s_configSystem =
                typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic);
            s_configSystem.SetValue(null, new ConfigSystem((IInternalConfigSystem)s_configSystem.GetValue(null)));
        }

        public ConfigSystem(IInternalConfigSystem baseconf)
        {
            this.baseconf = baseconf;
        }

        object appsettings;
        public object GetSection(string configKey)
        {
            if(configKey == "appSettings" && this.appsettings != null)
                return this.appsettings;
            object o = baseconf.GetSection(configKey);
            if(configKey == "appSettings" && o is NameValueCollection)
            {
                var cfg = new NameValueCollection((NameValueCollection)o);
                // Todo: Load category specific settings only
                CategoryAppSettings.Load(cfg);
                o = this.appsettings = cfg;
            }
            return o;
        }

        public void RefreshConfig(string sectionName)
        {
            if(sectionName == "appSettings" || sectionName == "CategorySection")
                appsettings = null;
            baseconf.RefreshConfig(sectionName);
        }

        public bool SupportsUserConfig
        {
            get
            {
                return baseconf.SupportsUserConfig;
            }
        }

    }
}